/**
 @Name：layui.tree 树组件
 @Author：贤心
 @License：LGPL

 */


layui.define(['jquery', 'tools'], function(exports){
    "use strict";

    var $ = layui.jquery;
    var hint = layui.hint();
    var t = layui.tools;

    var enterSkin = 'layui-tree-enter', Tree = function(options){
        this.options = options;
    };

    //图标
    var icon = {
        arrow: ['&#xe623;', '&#xe625;'] //箭头
        ,checkbox: ['&#xe626;', '&#xe627;'] //复选框
        ,radio: ['&#xe63f;', '&#xe643;'] //单选框
        ,branch: ['&#xe622;', '&#xe624;'] //父节点
        ,leaf: '&#xe621;' //叶节点
    };

    //初始化
    Tree.prototype.init = function(elem){
        var that = this;
        elem.addClass('layui-box layui-tree'); //添加tree样式
        if(that.options.skin){
            elem.addClass('layui-tree-skin-'+ that.options.skin);
        }
        that.tree(elem);
        if(that.options.check == 'checkbox'){
            if(!t.isEmpty(that.options.btnEvent)) {//自定义确定按钮
                if($('button.confirm-checkbox2').length == 0) {
                    $('<button class="layui-btn layui-btn-warm confirm-checkbox2" type="button" style="margin-left:10px;">确认</button>').insertAfter(that.options.elem);
                }
            }else{
                if($('button.confirm-checkbox').length == 0) {
                    $('<button class="layui-btn layui-btn-warm confirm-checkbox" type="button" style="margin-left:10px;">确认</button>').insertAfter(that.options.elem);
                }
            }
        }
        that.on(elem);
    };

    //树节点解析
    Tree.prototype.tree = function(elem, children){
        var that = this, options = that.options
        var nodes = children || options.nodes;
        var focusIds = options.focusId || [];
        layui.each(nodes, function(index, item){
            var id = parseInt(item.id);
            var hasChild = item.children && item.children.length > 0;
            var ul = $('<ul class="'+ (item.spread ? "layui-show" : "") +'"></ul>');
            var li = $(['<li '+ (item.spread ? 'data-spread="'+ item.spread +'"' : '') +' data-index="'+ item.index_show +'" data-parent="'+ item.parent_id +'">'
                //展开箭头
                ,function(){
                    return hasChild ? '<i class="layui-icon layui-tree-spread">'+ (
                        item.spread ? icon.arrow[1] : icon.arrow[0]
                    ) +'</i>' : '';
                }()

                //复选框/单选框
                ,function(){
                    var str = '';
                    if(options.check){
                        if($.inArray(item.id , focusIds) != -1){
                            str += '<i class="layui-icon layui-tree-check checked">';
                        }else{
                            str += '<i class="layui-icon layui-tree-check">';
                        }
                        if(options.check === 'checkbox'){
                            if($.inArray(item.id , focusIds) == -1 || focusIds.length == 0){
                                str += icon.checkbox[0];
                            }else {
                                str += icon.checkbox[1];
                            }
                        }else if(options.check === 'radio'){
                            if($.inArray(item.id , focusIds) == -1 || focusIds.length == 0){
                                str += icon.radio[0];
                            }else {
                                str += icon.radio[1];
                            }
                        }
                        str += '</i>';
                    }
                    return str;
                }()

                //节点
                ,function(){
                    var str = '<a href="'+ (item.href || 'javascript:;') +'" '+ (
                            options.target && item.href ? 'target=\"'+ options.target +'\"' : ''
                        ) +' data-id="'+ item.id +'">'
                        + ('<i class="layui-icon layui-tree-'+ (hasChild ? "branch" : "leaf") +'">'+ (
                            hasChild ? (
                                item.spread ? icon.branch[1] : icon.branch[0]
                            ) : icon.leaf
                        ) +'</i>')
                        //节点图标
                        + ('<cite>'+ (item.category_name||'未命名') +'</cite>');
                    str += ('</a>');

                    if(options.opera){
                        if(item.index_show == 0){
                            str += '<button class="layui-btn layui-btn-mini layui-btn-primary category_edit" data-type="show" data-show="'+ item.index_show +'" type="button">不显示</button>';
                        }else{
                            str += '<button class="layui-btn layui-btn-mini layui-btn-normal category_edit" data-type="show" data-show="'+ item.index_show +'" type="button">显　示</button>';
                        }
                        str += '<button class="layui-btn layui-btn-mini layui-btn-danger category_edit" data-type="del" type="button">删除</button>';
                        str += '<button class="layui-btn layui-btn-mini layui-btn-warm category_edit" data-type="edit" type="button">修改</button>';
                        if(item.category_type == 2){
                            str += '<button class="layui-btn layui-btn-mini category_edit" data-type="add" type="button">添加商品</button>';
                        }
                    }
                    return str;
                }()

                ,'</li>'].join(''));

            //如果有子节点，则递归继续生成树
            if(hasChild){
                li.append(ul);
                that.tree(ul, item.children);
            }

            elem.append(li);

            //选中聚焦
            if(focusIds.indexOf(id) > -1){
                that.eachTree($('a[data-id="'+ id +'"]').parent('li'));
            }

            //触发点击节点回调
            typeof options.click === 'function' && that.click(li, item);

            //伸展节点
            that.spread(li, item);

            //拖拽节点
            options.drag && that.drag(li, item);
        });
    };

    //点击节点回调
    Tree.prototype.click = function(elem, item){
        var that = this, options = that.options;
        elem.children('a').on('click', function(e){
            layui.stope(e);
            options.click(item)
        });
    };

    //伸展节点
    Tree.prototype.spread = function(elem, item) {
        var that = this, options = that.options;
        var arrow = elem.children('.layui-tree-spread');
        var checkElem = elem.children('.layui-tree-check');
        var ul = elem.children('ul'), a = elem.children('a');

        //执行伸展
        var open = function () {
            if (elem.data('spread')) {
                elem.data('spread', null)
                ul.removeClass('layui-show');
                arrow.html(icon.arrow[0]);
                a.find('.layui-icon').html(icon.branch[0]);
            } else {
                elem.data('spread', true);
                ul.addClass('layui-show');
                arrow.html(icon.arrow[1]);
                a.find('.layui-icon').html(icon.branch[1]);
            }
        };

        //执行选中
        var checked = function(){
            var type = $(that.options.elem).find('.layui-tree-check');
            if(that.options.check === 'radio'){
                type.removeClass('checked').html(icon.radio[0]);
                $(this).prev('.layui-tree-check').addClass('checked').html(icon.radio[1]);
            }else if(that.options.check === 'checkbox'){
                var currentLi = $(this).parent('li');
                if($(this).prev('.layui-tree-check').hasClass('checked')){
                    $(this).prev('.layui-tree-check').removeClass('checked').html(icon.checkbox[0]);
                }else{
                    $(this).prev('.layui-tree-check').addClass('checked').html(icon.checkbox[1]);
                }
                that.eachTree(currentLi);//li标签
            }
        };


        if ((options.check && options.check == 'radio') || (options.check && options.check == 'checkbox')){
            a.on('click', checked);
            checkElem.on('click', function(){
                $(this).next('a').click();
            });
        }
        //如果没有子节点，则不执行
        if (!ul[0]) return;

        arrow.on('click', open);
        //a.on('dblclick', open);
    }

    Tree.prototype.eachTree = function(obj){
    	var that = this, options = that.options;
        var objUl = obj.parent('ul');
        var objUlParentLi = objUl.parent('li');

        //判断当前是否取消选中
        if(!obj.find('i.layui-tree-check').hasClass('checked')){
            //判断当前兄弟分类选中数量
            var objBrotherLiChecked = objUl.find('i.layui-tree-check.checked').length;
            if(objBrotherLiChecked == 0){
                //取消父节点选中
                objUl.parent('li').find('i.layui-tree-check').removeClass('checked').html(icon.checkbox[0]);
            }
        }else{
            if(options.only){
                obj.siblings('li').find('i.layui-tree-check').removeClass('checked').html(icon.checkbox[0]);;
            }
            //判断父节点是否选中
            if(!objUlParentLi.find('i.layui-tree-check:first').hasClass('checked')){
                objUlParentLi.find('i.layui-tree-check:first').addClass('checked').html(icon.checkbox[1]);
            }
            /*if(that.options.check == 'checkbox'){
                var font = icon.checkbox;
            }else if(that.options.check == 'radio'){
                var font = icon.radio;
            }
            if(options.only){
                obj.siblings('li').find('i.layui-tree-check').removeClass('checked').html(font[0]);
            }
            //判断父节点是否选中
            if(!objUlParentLi.find('i.layui-tree-check:first').hasClass('checked')){
                objUlParentLi.find('i.layui-tree-check:first').addClass('checked').html(font[1]);
            }else{
                objUlParentLi.find('i.layui-tree-check:first').addClass('checked').html(font[0]);
            }*/
        }
        //判断当前父节点是否为最外层父亲节点
        if(objUlParentLi.attr('data-parent') > 0){
            this.eachTree(objUlParentLi);
        }
        //选中当前节点的子节点
        if(obj.find('ul').length > 0 && that.options.check === 'checkbox'){
            var objChild = obj.find('ul').children('li').find('i.layui-tree-check:first');
            if(that.options.check == 'checkbox'){
                if(!objChild.hasClass('checked')){
                    objChild.addClass('checked').html(icon.checkbox[1]);
                }else{
                    objChild.removeClass('checked').html(icon.checkbox[0]);
                }
            }else if(that.options.check == 'radio'){
                objChild.removeClass('checked').html(icon.radio[0]);
            }
        }

    }

    //通用事件
    Tree.prototype.on = function(elem){
        var that = this, options = that.options;
        var dragStr = 'layui-tree-drag';

        //屏蔽选中文字
        elem.find('i').on('selectstart', function(e){
            return false
        });

        //拖拽
        if(options.drag){
            $(document).on('mousemove', function(e){
                var move = that.move;
                if(move.from){
                    var to = move.to, treeMove = $('<div class="layui-box '+ dragStr +'"></div>');
                    e.preventDefault();
                    $('.' + dragStr)[0] || $('body').append(treeMove);
                    var dragElem = $('.' + dragStr)[0] ? $('.' + dragStr) : treeMove;
                    (dragElem).addClass('layui-show').html(move.from.elem.children('a').html());
                    dragElem.css({
                        left: e.pageX + 10
                        ,top: e.pageY + 10
                    })
                }
            }).on('mouseup', function(){
                var move = that.move;
                if(move.from){
                    move.from.elem.children('a').removeClass(enterSkin);
                    move.to && move.to.elem.children('a').removeClass(enterSkin);
                    that.move = {};
                    $('.' + dragStr).remove();
                }
            });
        }

        //多选确认
        $(document).on('click', 'button.confirm-checkbox,button.confirm-checkbox2', function(e){
            e.stopPropagation();
            e.preventDefault();
            var checkboxs = '', 
            	checkBoxName = [];
            $('i.layui-tree-check.checked').each(function(){
                var id = $(this).next('a').attr('data-id');
                checkboxs += id + ',';
                if(t.isEmpty(options.btnEvent)) {
                    checkBoxName.push($(this).next('a').children('cite').text());
                }
            });
            if(t.isEmpty(options.btnEvent)) {
                $('input[name="categroy_id"]').val(that.removeLastStr(checkboxs));
                if ($('.category-selected-list').length > 0) {
                    var html = '';
                    $(checkBoxName).each(function (i, e) {
                        html += '<button class="layui-btn layui-btn-mini layui-btn-warm" type="button">' + e + '</button>';
                    });
                    $('.category-selected-list').html(html);
                }
            }else{
                if(typeof options.btnEvent === 'function'){
                    options.btnEvent(that.removeLastStr(checkboxs));
                }
            }
            $('.category-list').addClass('layui-hide');
        });
    };

    //最后一位字符处理
    Tree.prototype.removeLastStr = function(str){
        str = str.substring(0, str.length-1);
        return str;
    };

    //拖拽节点
    Tree.prototype.move = {};
    Tree.prototype.drag = function(elem, item){
        var that = this, options = that.options;
        var a = elem.children('a'), mouseenter = function(){
            var othis = $(this), move = that.move;
            if(move.from){
                move.to = {
                    item: item
                    ,elem: elem
                };
                othis.addClass(enterSkin);
            }
        };
        a.on('mousedown', function(){
            var move = that.move
            move.from = {
                item: item
                ,elem: elem
            };
        });
        a.on('mouseenter', mouseenter).on('mousemove', mouseenter)
            .on('mouseleave', function(){
                var othis = $(this), move = that.move;
                if(move.from){
                    delete move.to;
                    othis.removeClass(enterSkin);
                }
            });
    };

    //暴露接口
    exports('tree', function(options){
        var tree = new Tree(options = options || {});
        var elem = $(options.elem);
        if(!elem[0]){
            return hint.error('layui.tree 没有找到'+ options.elem +'元素');
        }
        tree.init(elem);
    });
});